package test;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @ClassName T3
 * @Description
 * @Author Jingxiao.Ye
 * @Date 2021/8/8 下午5:57
 * @Version V1.0
 * @Since JDK 11
 */
public class T3 {

    public static void main(String[] args) {
        System.out.println(fieldSum(new int[]{4,3,7,1}));
    }

    public static int fieldSum(int[] v) {
        Deque<Integer> deque = new ArrayDeque();
        int result = 0;
        for (int i = 0; i < v.length; i++) {
            Integer index = null;
            while (deque.peekLast() != null && v[deque.peekLast()] <= v[i]) {
                Integer c = deque.pollLast();
                if(index == null){
                    index = c;
                }else {
                    result += (index-c);
                }
            }
            deque.offerLast(i);
        }
        //最后一个结算
        Integer index = null;
        while (!deque.isEmpty()) {
            Integer c = deque.pollLast();
            if(index == null){
                index = c;
            }else {
                result += (index-c);
            }
        }
        return result;
    }
}
